<template>
  <div class="post-container">
    <!-- 页面布局 - 分为左侧部门树和右侧岗位列表 -->
    <el-row :gutter="20">
      <!-- 左侧部门树 -->
      <el-col :span="5">
        <el-card class="dept-card">
          <div class="tree-header">
            <span>部门列表</span>
            <el-button
              type="text"
              icon="el-icon-refresh"
              @click="getDeptTree"
              title="刷新部门树"
            ></el-button>
          </div>
          <el-tree
            v-if="deptTreeData.length > 0"
            :data="deptTreeData"
            :props="{ label: 'deptName', children: 'children' }"
            node-key="deptId"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleDeptNodeClick"
          ></el-tree>
          <div v-else class="tree-empty-tip">暂无部门数据</div>
          <div class="clear-filter" v-if="selectedDeptId">
            <el-button type="text" @click="clearDeptFilter">清除部门筛选</el-button>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧岗位列表 -->
      <el-col :span="19">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-card class="search-card">
            <el-form :inline="true" :model="queryParams" ref="queryForm" id="queryForm">
              <el-form-item label="岗位名称" prop="postName">
                <el-input v-model="queryParams.postName" placeholder="请输入岗位名称" clearable style="width: 200px" />
              </el-form-item>
              <el-form-item label="岗位编码" prop="postCode">
                <el-input v-model="queryParams.postCode" placeholder="请输入岗位编码" clearable style="width: 200px" />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="岗位状态" clearable style="width: 200px">
                  <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
        
        <!-- 操作按钮区域 -->
        <div class="action-container">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          <el-button icon="el-icon-edit" :disabled="single" @click="handleUpdate">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" :disabled="multiple" @click="handleDelete">删除</el-button>
          <el-button icon="el-icon-download" @click="handleExport">导出</el-button>
        </div>
        
        <!-- 表格区域 -->
        <el-card class="table-card">
          <!-- 显示当前筛选状态 -->
          <div class="filter-info" v-if="selectedDeptId">
            <el-tag type="info">
              当前筛选: {{ getCurrentDeptName() }}
              <i class="el-icon-close" @click="clearDeptFilter"></i>
            </el-tag>
          </div>
          
          <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange" border>
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="岗位编号" align="center" prop="postId" />
            <el-table-column label="岗位编码" align="center" prop="postCode" :show-overflow-tooltip="true" />
            <el-table-column label="岗位名称" align="center" prop="postName" :show-overflow-tooltip="true" />
            <el-table-column label="所属部门" align="center" prop="deptName" :show-overflow-tooltip="true" />
            <el-table-column label="岗位排序" align="center" prop="postSort" />
            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
            <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 没有数据时显示提示 -->
          <div v-if="postList.length === 0 && !loading" class="empty-data">
            <el-empty description="暂无数据"></el-empty>
          </div>
          
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="postFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select
            v-model="form.deptId"
            :data="deptTreeData"
            :props="{ label: 'deptName', children: 'children', value: 'deptId' }"
            placeholder="请选择所属部门"
            :render-after-expand="false"
            style="width: 100%"
            @change="handleDeptSelectChange"
          />
        </el-form-item>
        <el-form-item label="岗位名称" prop="postName">
          <el-input v-model="form.postName" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="岗位编码" prop="postCode">
          <el-input v-model="form.postCode" placeholder="请输入岗位编码" />
        </el-form-item>
        <el-form-item label="岗位顺序" prop="postSort">
          <el-input-number v-model="form.postSort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item label="岗位状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPostList, getPostDetail, addPost, updatePost, deletePost, updatePostStatus, exportPost } from '@/api/system/post'
import { getDeptTreeList } from '@/api/system/dept' // 导入获取部门树的API

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 岗位表格数据
const postList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 部门树数据
const deptTreeData = ref([])
// 当前选中的部门ID
const selectedDeptId = ref(null)

// 表单参数
const form = reactive({
  postId: undefined,
  deptId: undefined,
  postName: undefined,
  postCode: undefined,
  postSort: 0,
  status: "0",
  remark: undefined
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  postName: undefined,
  postCode: undefined,
  status: undefined,
  deptId: undefined
})

// 表单校验
const rules = reactive({
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "change" }],
  postName: [{ required: true, message: "岗位名称不能为空", trigger: "blur" }],
  postCode: [{ required: true, message: "岗位编码不能为空", trigger: "blur" }],
  postSort: [{ required: true, message: "岗位顺序不能为空", trigger: "number" }]
})

// 状态数据字典
const statusOptions = [
  { value: "0", label: "正常" },
  { value: "1", label: "停用" }
]

const postFormRef = ref(null)

/** 查询岗位列表 */
function getList() {
  loading.value = true
  getPostList(queryParams).then(response => {
    if (response && response.data) {
      postList.value = response.data.list || []
      total.value = response.data.total || 0
    } else {
      postList.value = []
      total.value = 0
    }
    loading.value = false
  }).catch(error => {
    console.error('获取岗位列表出错:', error)
    postList.value = []
    total.value = 0
    loading.value = false
  })
}

/** 获取部门树结构 */
function getDeptTree() {
  getDeptTreeList().then(response => {
    console.log('部门树API返回数据:', response)
    
    // 处理数据格式，兼容不同的返回结构
    let deptData
    if (response.data) {
      // 真实API可能返回的格式
      deptData = response.data
    } else if (Array.isArray(response)) {
      // 模拟数据可能直接返回数组
      deptData = response
    } else {
      // 默认为空数组
      deptData = []
    }
    
    // 确保是数组
    deptTreeData.value = Array.isArray(deptData) ? deptData : []
    
    console.log('处理后的部门树数据:', deptTreeData.value)
    
    // 如果部门树为空，添加一个提示
    if (deptTreeData.value.length === 0) {
      console.warn('部门树数据为空')
    }
  }).catch(error => {
    console.error('获取部门树结构出错:', error)
    deptTreeData.value = []
  })
}

/** 获取当前选中部门的名称 */
function getCurrentDeptName() {
  if (!selectedDeptId.value) return ""
  
  // 递归查找部门名称
  const findDeptName = (deptList, deptId) => {
    for (const dept of deptList) {
      if (dept.deptId === selectedDeptId.value) {
        return dept.deptName
      }
      if (dept.children && dept.children.length > 0) {
        const childResult = findDeptName(dept.children, deptId)
        if (childResult) return childResult
      }
    }
    return null
  }
  
  const deptName = findDeptName(deptTreeData.value, selectedDeptId.value)
  return deptName || `部门ID: ${selectedDeptId.value}`
}

/** 处理部门树节点点击 */
function handleDeptNodeClick(data) {
  selectedDeptId.value = data.deptId
  // 将选中的部门ID转换为数字
  queryParams.deptId = parseInt(data.deptId)
  // 每次选择部门后重置分页到第一页
  queryParams.pageNum = 1
  getList()
}

/** 清除部门筛选 */
function clearDeptFilter() {
  selectedDeptId.value = null
  queryParams.deptId = undefined
  getList()
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.postId = undefined
  form.deptId = undefined
  form.postName = undefined
  form.postCode = undefined
  form.postSort = 0
  form.status = "0"
  form.remark = undefined
  
  // 如果表单引用存在，重置表单校验状态
  if (postFormRef.value) {
    postFormRef.value.resetFields()
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  // 保留部门选择
  const deptId = queryParams.deptId
  
  // 重置查询表单
  if (document.querySelector('#queryForm')) {
    document.querySelector('#queryForm').reset()
  }
  
  queryParams.postName = undefined
  queryParams.postCode = undefined
  queryParams.status = undefined
  
  // 恢复部门ID
  queryParams.deptId = deptId
  
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.postId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  if (selectedDeptId.value) {
    form.deptId = selectedDeptId.value
  }
  open.value = true
  title.value = "添加岗位"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const postId = row.postId || ids.value[0]
  getPostDetail(postId).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = "修改岗位"
  }).catch(error => {
    console.error('获取岗位详情出错:', error)
    ElMessage.error('获取岗位信息失败')
  })
}

/** 处理部门选择变化 */
function handleDeptSelectChange(deptId) {
  if (!deptId) {
    return;
  }
  
  // 查找选中部门的名称
  const findDeptName = (deptList, deptId) => {
    for (const dept of deptList) {
      if (dept.deptId === deptId) {
        // 自动生成岗位编码前缀
        if (!form.postCode || form.postCode.startsWith('DEPT')) {
          form.postCode = `DEPT${deptId}_POST`;
        }
        return dept.deptName;
      }
      if (dept.children && dept.children.length > 0) {
        const childResult = findDeptName(dept.children, deptId);
        if (childResult) return childResult;
      }
    }
    return null;
  };
  
  const deptName = findDeptName(deptTreeData.value, deptId);
  if (deptName) {
    // 如果是新增模式，自动填充岗位名称前缀
    if (!form.postId && (!form.postName || form.postName.startsWith(form.deptName || ''))) {
      form.postName = `${deptName}岗位`;
    }
    
    form.deptName = deptName;
  }
}

/** 提交按钮 */
function submitForm() {
  // 确保表单引用存在
  if (!postFormRef.value) {
    console.error('表单引用不存在')
    return
  }

  postFormRef.value.validate(valid => {
    if (valid) {
      // 确保deptId是数字类型
      if (form.deptId) {
        form.deptId = parseInt(form.deptId);
      }
      
      if (form.postId) {
        updatePost(form).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        }).catch(error => {
          console.error('修改岗位出错:', error)
          ElMessage.error('修改岗位失败')
        })
      } else {
        addPost(form).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        }).catch(error => {
          console.error('新增岗位出错:', error)
          ElMessage.error('新增岗位失败')
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const postIds = row.postId || ids.value
  
  if (!postIds || (Array.isArray(postIds) && postIds.length === 0)) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm("是否确认删除岗位编号为" + postIds + "的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deletePost(postIds).then(() => {
      ElMessage.success("删除成功")
      getList()
    }).catch(error => {
      console.error('删除岗位出错:', error)
      ElMessage.error('删除岗位失败')
    })
  }).catch(() => {
    // 用户取消删除操作，不做任何处理
  })
}

/** 导出按钮操作 */
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有岗位数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    exportPost(queryParams).then(() => {
      ElMessage.success('导出成功')
    }).catch(() => {
      ElMessage.error('导出失败')
    })
  })
}

/** 岗位状态修改 */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用"
  ElMessageBox.confirm("确认要" + text + "该岗位吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    updatePostStatus({
      postId: row.postId,
      status: row.status
    }).then(() => {
      ElMessage.success(text + "成功")
    }).catch(error => {
      console.error('更新岗位状态出错:', error)
      // 恢复之前的状态
      row.status = row.status === "0" ? "1" : "0"
      ElMessage.error(text + "失败")
    })
  }).catch(() => {
    row.status = row.status === "0" ? "1" : "0"
  })
}

onMounted(() => {
  getDeptTree()
  getList()
})
</script>

<style scoped>
.post-container {
  padding: 10px;
}

.dept-card {
  height: 100%;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.search-container {
  margin-bottom: 10px;
}

.search-card {
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.action-container {
  margin-bottom: 10px;
  padding: 5px 0;
}

.table-card {
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.tree-empty-tip {
  color: #909399;
  text-align: center;
  padding: 20px 0;
}

.clear-filter {
  margin-top: 10px;
  text-align: center;
}

.filter-info {
  margin-bottom: 10px;
}

.el-tag .el-icon-close {
  margin-left: 5px;
  cursor: pointer;
}

.empty-data {
  padding: 30px 0;
}
</style> 